<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🐍 AI贪吃蛇</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&display=swap');
        
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            font-family: 'Orbitron', monospace;
            overflow: hidden;
        }
        
        .game-container {
            text-align: center;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            padding: 30px;
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
            animation: glow 2s ease-in-out infinite alternate;
        }
        
        @keyframes glow {
            from { box-shadow: 0 8px 32px rgba(0,0,0,0.3); }
            to { box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4); }
        }
        
        .game-info {
            color: white;
            margin-bottom: 25px;
        }
        
        .game-title {
            font-size: 28px;
            font-weight: 900;
            margin-bottom: 15px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
            background: linear-gradient(45deg, #fff, #a8edea);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .score-container {
            display: flex;
            justify-content: space-around;
            margin-bottom: 15px;
        }
        
        .score {
            font-size: 20px;
            font-weight: 700;
            color: #fff;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
        }
        
        .score-value {
            color: #00ff88;
            font-size: 24px;
            text-shadow: 0 0 10px rgba(0, 255, 136, 0.5);
        }
        
        .speed-indicator {
            font-size: 16px;
            color: #ff6b6b;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
        }
        
        .controls {
            font-size: 14px;
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 20px;
            font-weight: 400;
        }
        
        canvas {
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 10px;
            background-color: #0f1419;
            box-shadow: 0 0 20px rgba(0,0,0,0.5);
            transition: transform 0.3s ease;
        }
        
        canvas:hover {
            transform: scale(1.02);
        }
        
        .game-over {
            color: #ff4757;
            font-size: 24px;
            font-weight: 700;
            margin-top: 15px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .restart-btn {
            background: linear-gradient(45deg, #00ff88, #00d4aa);
            color: #0f1419;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 700;
            margin-top: 15px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 255, 136, 0.3);
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .restart-btn:hover {
            background: linear-gradient(45deg, #00d4aa, #00ff88);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 255, 136, 0.5);
        }
        
        .restart-btn:active {
            transform: translateY(0);
        }
        
        @keyframes scoreFloat {
            0% {
                transform: translateY(0) scale(1);
                opacity: 1;
            }
            50% {
                transform: translateY(-20px) scale(1.2);
                opacity: 1;
            }
            100% {
                transform: translateY(-40px) scale(0.8);
                opacity: 0;
            }
        }
    </style>
</head>
<body>
    <div class="game-container">
        <div class="game-info">
            <div class="game-title">🐍 AI贪吃蛇</div>
            <div class="score-container">
                <div class="score">得分: <span id="score" class="score-value">0</span></div>
                <div class="speed-indicator">速度: <span id="speed">1.0x</span></div>
            </div>
            <div class="controls">🤖 AI智能寻食模式 | 自动运行</div>
        </div>
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        <div id="gameOver" class="game-over" style="display: none;">
            游戏结束！
            <br>
            <button class="restart-btn" onclick="restartGame()">重新开始</button>
        </div>
    </div>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const gameOverElement = document.getElementById('gameOver');
        const speedElement = document.getElementById('speed');

        const gridSize = 20;
        const tileCount = canvas.width / gridSize;

        let snake = [
            {x: 10, y: 10}
        ];
        let dx = 1;
        let dy = 0;
        let foodX = 15;
        let foodY = 15;
        let score = 0;
        let gameRunning = true;
        let baseSpeed = 200; // 从100调整为200，速度减半
        let eatingAnimation = false;
        let animationFrame = 0;
        let manualControl = false;

        function generateFood() {
            foodX = Math.floor(Math.random() * tileCount);
            foodY = Math.floor(Math.random() * tileCount);
            
            for (let segment of snake) {
                if (segment.x === foodX && segment.y === foodY) {
                    generateFood();
                    return;
                }
            }
        }

        function findPathToFood() {
            const head = snake[0];
            const target = {x: foodX, y: foodY};
            console.log("Finding path from", head.x, head.y, "to food at", foodX, foodY);
            
            const directions = [
                {dx: 0, dy: -1}, // 上
                {dx: 0, dy: 1},  // 下
                {dx: -1, dy: 0}, // 左
                {dx: 1, dy: 0}   // 右
            ];
            
            // 简化策略：首先尝试朝食物方向移动
            const foodDirection = {
                dx: foodX > head.x ? 1 : foodX < head.x ? -1 : 0,
                dy: foodY > head.y ? 1 : foodY < head.y ? -1 : 0
            };
            
            // 检查食物方向是否安全
            const foodDirIndex = directions.findIndex(dir => dir.dx === foodDirection.dx && dir.dy === foodDirection.dy);
            if (foodDirIndex !== -1) {
                const newX = head.x + foodDirection.dx;
                const newY = head.y + foodDirection.dy;
                
                if (newX >= 0 && newX < tileCount && newY >= 0 && newY < tileCount) {
                    // 检查是否会撞到自己（除了尾部）
                    let collision = false;
                    for (let i = 0; i < snake.length - 1; i++) {
                        if (snake[i].x === newX && snake[i].y === newY) {
                            collision = true;
                            break;
                        }
                    }
                    
                    if (!collision) {
                        dx = foodDirection.dx;
                        dy = foodDirection.dy;
                        console.log("Moving towards food:", dx, dy);
                        return;
                    }
                }
            }
            
            // 如果不能直接朝食物移动，寻找任何安全方向
            const safeDirections = [];
            
            for (let dir of directions) {
                const newX = head.x + dir.dx;
                const newY = head.y + dir.dy;
                
                // 检查边界
                if (newX < 0 || newX >= tileCount || newY < 0 || newY >= tileCount) {
                    continue;
                }
                
                // 检查与自身的碰撞（除了尾部）
                let collision = false;
                for (let i = 0; i < snake.length - 1; i++) {
                    if (snake[i].x === newX && snake[i].y === newY) {
                        collision = true;
                        break;
                    }
                }
                
                if (!collision) {
                    safeDirections.push(dir);
                }
            }
            
            // 如果有安全方向，选择最接近食物的
            if (safeDirections.length > 0) {
                let bestDir = safeDirections[0];
                let minDistance = Infinity;
                
                for (let dir of safeDirections) {
                    const newX = head.x + dir.dx;
                    const newY = head.y + dir.dy;
                    const distance = Math.abs(newX - foodX) + Math.abs(newY - foodY);
                    
                    if (distance < minDistance) {
                        minDistance = distance;
                        bestDir = dir;
                    }
                }
                
                dx = bestDir.dx;
                dy = bestDir.dy;
                console.log("Selected safe direction:", dx, dy);
                return;
            }
            
            // 如果没有安全方向，尝试穿越尾部
            for (let dir of directions) {
                const newX = head.x + dir.dx;
                const newY = head.y + dir.dy;
                
                if (newX >= 0 && newX < tileCount && newY >= 0 && newY < tileCount) {
                    // 检查是否只有尾部阻挡
                    let onlyTail = true;
                    for (let i = 0; i < snake.length - 1; i++) {
                        if (snake[i].x === newX && snake[i].y === newY) {
                            onlyTail = false;
                            break;
                        }
                    }
                    
                    if (onlyTail) {
                        dx = dir.dx;
                        dy = dir.dy;
                        console.log("Moving through tail:", dx, dy);
                        return;
                    }
                }
            }
            
            // 最后手段：随机选择一个不撞墙的方向
            const validDirections = directions.filter(dir => {
                const newX = head.x + dir.dx;
                const newY = head.y + dir.dy;
                return newX >= 0 && newX < tileCount && newY >= 0 && newY < tileCount;
            });
            
            if (validDirections.length > 0) {
                const randomDir = validDirections[Math.floor(Math.random() * validDirections.length)];
                dx = randomDir.dx;
                dy = randomDir.dy;
                console.log("Random direction selected:", dx, dy);
                return;
            }
            
            // 如果所有方向都撞墙，保持当前方向
            console.log("All directions blocked, keeping current direction:", dx, dy);
        }
        
        function checkFutureSafety(x, y, steps) {
            let safetyScore = 0;
            const visited = new Set();
            const queue = [{x, y, step: 0}];
            
            while (queue.length > 0) {
                const current = queue.shift();
                const key = `${current.x},${current.y}`;
                
                if (visited.has(key) || current.step >= steps) {
                    continue;
                }
                
                visited.add(key);
                safetyScore += 10;
                
                // 检查四个方向
                const directions = [
                    {dx: 0, dy: -1}, {dx: 0, dy: 1},
                    {dx: -1, dy: 0}, {dx: 1, dy: 0}
                ];
                
                for (let dir of directions) {
                    const newX = current.x + dir.dx;
                    const newY = current.y + dir.dy;
                    
                    if (newX >= 0 && newX < tileCount && newY >= 0 && newY < tileCount) {
                        let collision = false;
                        for (let segment of snake) {
                            if (segment.x === newX && segment.y === newY) {
                                collision = true;
                                break;
                            }
                        }
                        
                        if (!collision) {
                            queue.push({x: newX, y: newY, step: current.step + 1});
                        }
                    }
                }
            }
            
            return safetyScore;
        }

        function getCurrentSpeed() {
            return Math.max(80, baseSpeed - Math.floor(score / 80) * 16); // 最低速度从40调整到80，递增值从8调整到16
        }

        function drawGame() {
            if (!gameRunning) {
                console.log("Game stopped, not running");
                return;
            }

            clearCanvas();
            
            // 只在自动控制模式下调用AI路径寻找
            if (!manualControl) {
                findPathToFood();
            }
            
            moveSnake();
            
            if (checkGameOver()) {
                gameRunning = false;
                gameOverElement.style.display = 'block';
                console.log("Game over detected");
                return;
            }
            
            checkFoodCollision();
            drawSnake();
            drawFood();
            
            const nextSpeed = getCurrentSpeed();
            console.log("Scheduling next frame in", nextSpeed, "ms");
            setTimeout(drawGame, nextSpeed);
        }

        function clearCanvas() {
            ctx.fillStyle = '#1a252f';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        }

        function drawSnake() {
            for (let i = 0; i < snake.length; i++) {
                const segment = snake[i];
                const x = segment.x * gridSize;
                const y = segment.y * gridSize;
                
                if (i === 0) {
                    // 蛇头 - 圆形设计
                    ctx.beginPath();
                    ctx.arc(x + gridSize/2, y + gridSize/2, gridSize/2 - 2, 0, 2 * Math.PI);
                    
                    const gradient = ctx.createRadialGradient(
                        x + gridSize/2, y + gridSize/2, 0,
                        x + gridSize/2, y + gridSize/2, gridSize/2
                    );
                    gradient.addColorStop(0, '#4ecdc4');
                    gradient.addColorStop(0.7, '#44a08d');
                    gradient.addColorStop(1, '#093637');
                    
                    ctx.fillStyle = gradient;
                    ctx.fill();
                    
                    // 蛇头眼睛
                    ctx.fillStyle = '#fff';
                    ctx.beginPath();
                    ctx.arc(x + gridSize/3, y + gridSize/3, 2, 0, 2 * Math.PI);
                    ctx.arc(x + 2*gridSize/3, y + gridSize/3, 2, 0, 2 * Math.PI);
                    ctx.fill();
                    
                    // 眼珠
                    ctx.fillStyle = '#000';
                    ctx.beginPath();
                    ctx.arc(x + gridSize/3, y + gridSize/3, 1, 0, 2 * Math.PI);
                    ctx.arc(x + 2*gridSize/3, y + gridSize/3, 1, 0, 2 * Math.PI);
                    ctx.fill();
                    
                    // 根据移动方向调整眼睛位置
                    if (dx === 1) { // 向右
                        ctx.fillStyle = '#fff';
                        ctx.beginPath();
                        ctx.arc(x + 2*gridSize/3, y + gridSize/3, 2, 0, 2 * Math.PI);
                        ctx.arc(x + 2*gridSize/3, y + 2*gridSize/3, 2, 0, 2 * Math.PI);
                        ctx.fill();
                        ctx.fillStyle = '#000';
                        ctx.beginPath();
                        ctx.arc(x + 2*gridSize/3, y + gridSize/3, 1, 0, 2 * Math.PI);
                        ctx.arc(x + 2*gridSize/3, y + 2*gridSize/3, 1, 0, 2 * Math.PI);
                        ctx.fill();
                    } else if (dx === -1) { // 向左
                        ctx.fillStyle = '#fff';
                        ctx.beginPath();
                        ctx.arc(x + gridSize/3, y + gridSize/3, 2, 0, 2 * Math.PI);
                        ctx.arc(x + gridSize/3, y + 2*gridSize/3, 2, 0, 2 * Math.PI);
                        ctx.fill();
                        ctx.fillStyle = '#000';
                        ctx.beginPath();
                        ctx.arc(x + gridSize/3, y + gridSize/3, 1, 0, 2 * Math.PI);
                        ctx.arc(x + gridSize/3, y + 2*gridSize/3, 1, 0, 2 * Math.PI);
                        ctx.fill();
                    } else if (dy === -1) { // 向上
                        ctx.fillStyle = '#fff';
                        ctx.beginPath();
                        ctx.arc(x + gridSize/3, y + gridSize/3, 2, 0, 2 * Math.PI);
                        ctx.arc(x + 2*gridSize/3, y + gridSize/3, 2, 0, 2 * Math.PI);
                        ctx.fill();
                        ctx.fillStyle = '#000';
                        ctx.beginPath();
                        ctx.arc(x + gridSize/3, y + gridSize/3, 1, 0, 2 * Math.PI);
                        ctx.arc(x + 2*gridSize/3, y + gridSize/3, 1, 0, 2 * Math.PI);
                        ctx.fill();
                    } else if (dy === 1) { // 向下
                        ctx.fillStyle = '#fff';
                        ctx.beginPath();
                        ctx.arc(x + gridSize/3, y + 2*gridSize/3, 2, 0, 2 * Math.PI);
                        ctx.arc(x + 2*gridSize/3, y + 2*gridSize/3, 2, 0, 2 * Math.PI);
                        ctx.fill();
                        ctx.fillStyle = '#000';
                        ctx.beginPath();
                        ctx.arc(x + gridSize/3, y + 2*gridSize/3, 1, 0, 2 * Math.PI);
                        ctx.arc(x + 2*gridSize/3, y + 2*gridSize/3, 1, 0, 2 * Math.PI);
                        ctx.fill();
                    }
                    
                } else {
                    // 蛇身 - 渐变圆形，从头部到尾部逐渐变小
                    const size = gridSize/2 - 1 - (i * 0.1);
                    const finalSize = Math.max(size, gridSize/3);
                    
                    ctx.beginPath();
                    ctx.arc(x + gridSize/2, y + gridSize/2, finalSize, 0, 2 * Math.PI);
                    
                    const gradient = ctx.createRadialGradient(
                        x + gridSize/2, y + gridSize/2, 0,
                        x + gridSize/2, y + gridSize/2, finalSize
                    );
                    
                    const colorIntensity = Math.max(0.3, 1 - (i / snake.length) * 0.7);
                    gradient.addColorStop(0, `rgba(78, 205, 196, ${colorIntensity})`);
                    gradient.addColorStop(0.5, `rgba(68, 160, 141, ${colorIntensity})`);
                    gradient.addColorStop(1, `rgba(9, 54, 55, ${colorIntensity})`);
                    
                    ctx.fillStyle = gradient;
                    ctx.fill();
                }
                
                // 添加光晕效果
                ctx.shadowColor = i === 0 ? '#4ecdc4' : '#44a08d';
                ctx.shadowBlur = 8;
                if (i === 0) {
                    ctx.beginPath();
                    ctx.arc(x + gridSize/2, y + gridSize/2, gridSize/2 - 2, 0, 2 * Math.PI);
                    ctx.fill();
                } else {
                    const size = gridSize/2 - 1 - (i * 0.1);
                    const finalSize = Math.max(size, gridSize/3);
                    ctx.beginPath();
                    ctx.arc(x + gridSize/2, y + gridSize/2, finalSize, 0, 2 * Math.PI);
                    ctx.fill();
                }
                ctx.shadowBlur = 0;
            }
        }

        function drawFood() {
            // 食物 - 发光效果
            const centerX = foodX * gridSize + gridSize/2;
            const centerY = foodY * gridSize + gridSize/2;
            
            // 吃食动画效果
            let scale = 1;
            let opacity = 1;
            if (eatingAnimation) {
                scale = 1 + Math.sin(animationFrame * 0.5) * 0.3;
                opacity = 1 - (animationFrame / 20);
                animationFrame++;
                
                if (animationFrame > 20) {
                    eatingAnimation = false;
                    animationFrame = 0;
                }
            }
            
            ctx.save();
            ctx.globalAlpha = opacity;
            ctx.translate(centerX, centerY);
            ctx.scale(scale, scale);
            ctx.translate(-centerX, -centerY);
            
            const gradient = ctx.createRadialGradient(
                centerX, centerY, 0,
                centerX, centerY, gridSize/2
            );
            gradient.addColorStop(0, '#ff6b6b');
            gradient.addColorStop(1, '#ff4757');
            
            ctx.fillStyle = gradient;
            ctx.fillRect(foodX * gridSize + 1, foodY * gridSize + 1, gridSize - 2, gridSize - 2);
            
            // 添加脉冲效果
            const pulseSize = eatingAnimation ? 15 + Math.sin(animationFrame * 0.3) * 5 : 10;
            ctx.shadowColor = '#ff6b6b';
            ctx.shadowBlur = pulseSize;
            ctx.fillRect(foodX * gridSize + 1, foodY * gridSize + 1, gridSize - 2, gridSize - 2);
            ctx.shadowBlur = 0;
            
            ctx.restore();
        }

        function moveSnake() {
            const head = {x: snake[0].x + dx, y: snake[0].y + dy};
            console.log("Moving snake to:", head.x, head.y, "Current direction:", dx, dy);
            snake.unshift(head);
            
            // 总是移除尾部，增长逻辑在checkFoodCollision中处理
            snake.pop();
        }

        function updateSpeedDisplay() {
            const currentSpeed = getCurrentSpeed();
            const speedMultiplier = (100 / currentSpeed).toFixed(1);
            speedElement.textContent = speedMultiplier + 'x';
        }

        function checkFoodCollision() {
            if (snake[0].x === foodX && snake[0].y === foodY) {
                console.log("Food eaten! Current snake length:", snake.length);
                score += 10;
                scoreElement.textContent = score;
                updateSpeedDisplay();
                
                // 触发吃食动画
                eatingAnimation = true;
                animationFrame = 0;
                
                // 显示得分提示
                showScorePopup();
                
                // 蛇吃食物后增长 - 添加一个尾部节点
                const tail = snake[snake.length - 1];
                snake.push({x: tail.x, y: tail.y});
                console.log("Snake grew to length:", snake.length);
                
                generateFood();
                console.log("New food generated at:", foodX, foodY);
            }
        }
        
        function showScorePopup() {
            const popup = document.createElement('div');
            popup.textContent = '+10';
            popup.style.cssText = `
                position: absolute;
                color: #00ff88;
                font-size: 24px;
                font-weight: bold;
                font-family: 'Orbitron', monospace;
                text-shadow: 0 0 10px rgba(0, 255, 136, 0.8);
                pointer-events: none;
                z-index: 1000;
                animation: scoreFloat 1s ease-out forwards;
            `;
            
            // 计算食物在屏幕上的位置
            const canvasRect = canvas.getBoundingClientRect();
            popup.style.left = (canvasRect.left + foodX * gridSize + gridSize/2) + 'px';
            popup.style.top = (canvasRect.top + foodY * gridSize + gridSize/2) + 'px';
            
            document.body.appendChild(popup);
            
            // 1秒后移除
            setTimeout(() => {
                document.body.removeChild(popup);
            }, 1000);
        }

        function checkGameOver() {
            const head = snake[0];
            
            if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
                return true;
            }
            
            for (let i = 1; i < snake.length; i++) {
                if (head.x === snake[i].x && head.y === snake[i].y) {
                    return true;
                }
            }
            
            return false;
        }

        function restartGame() {
            snake = [{x: 10, y: 10}];
            dx = 1;
            dy = 0;
            score = 0;
            scoreElement.textContent = score;
            speedElement.textContent = '1.0x';
            gameOverElement.style.display = 'none';
            gameRunning = true;
            baseSpeed = 100;
            eatingAnimation = false;
            animationFrame = 0;
            manualControl = false; // 重置为自动控制
            updateControlDisplay();
            generateFood();
            drawGame();
        }

        // 键盘控制 - 按任意方向键切换到人工控制
        document.addEventListener('keydown', (e) => {
            if (!gameRunning) return;
            
            let newDx = dx;
            let newDy = dy;
            let keyPressed = false;
            
            switch(e.key) {
                case 'ArrowUp':
                    if (dy !== 1) { // 不能直接反向
                        newDx = 0;
                        newDy = -1;
                        keyPressed = true;
                    }
                    break;
                case 'ArrowDown':
                    if (dy !== -1) { // 不能直接反向
                        newDx = 0;
                        newDy = 1;
                        keyPressed = true;
                    }
                    break;
                case 'ArrowLeft':
                    if (dx !== 1) { // 不能直接反向
                        newDx = -1;
                        newDy = 0;
                        keyPressed = true;
                    }
                    break;
                case 'ArrowRight':
                    if (dx !== -1) { // 不能直接反向
                        newDx = 1;
                        newDy = 0;
                        keyPressed = true;
                    }
                    break;
            }
            
            if (keyPressed) {
                e.preventDefault(); // 防止页面滚动
                
                // 如果之前是自动控制，切换到人工控制
                if (!manualControl) {
                    manualControl = true;
                    console.log("Switched to manual control");
                    updateControlDisplay();
                }
                
                dx = newDx;
                dy = newDy;
                console.log("Manual control:", dx, dy);
            }
        });

        function updateControlDisplay() {
            const controlsElement = document.querySelector('.controls');
            if (manualControl) {
                controlsElement.textContent = '🎮 人工控制模式 | 使用方向键控制';
                controlsElement.style.color = '#ff6b6b';
            } else {
                controlsElement.textContent = '🤖 AI智能寻食模式 | 自动运行';
                controlsElement.style.color = 'rgba(255, 255, 255, 0.8)';
            }
        }

        generateFood();
        drawGame();
    </script>
</body>
</html>